<script setup>
import { appStore } from '@/sotre/modules/app';

const { userInfo } = toRefs(appStore());

const $get = inject('$get');
const $post = inject('$post');

const list = ref([]);
const dicts = ref([]);
// 控制每个套餐的折叠状态，key为套餐id，value为是否展开
const collapseValues = ref({});

$get('/human/packages/usablePackage').then(res => {
    list.value = res.data;
    // 初始化折叠状态，默认全部收起
    res.data.forEach(item => {
        collapseValues.value[item.id] = [];
    });
});

$get(`/system/dict/data/type/unit`).then(res => {
    dicts.value = res.data;
});

// 格式化单位显示（根据图片格式：个 或 时长/分）
const formatUnit = unitValue => {
    // unit为"0"显示"个"，unit为"3"显示"时长/分"
    if (unitValue === '0' || unitValue === 0) {
        return '个';
    } else if (unitValue === '3' || unitValue === 3) {
        return '时长/分';
    }
    // 如果dicts中有对应值，使用dicts的值
    const dict = dicts.value.find(item => item.dictValue === String(unitValue));
    return dict ? dict.dictLabel : '';
};

// 购买处理
const handleBuy = item => {
    // 检查是否为主账号
    if (!userInfo.value.currEnterpriseByCache?.main) {
        return uni.showToast({
            title: '您不是当前企业主账号，暂无权限充值',
            icon: 'none',
            duration: 2000,
        });
    }
    // TODO: 实现购买逻辑
    uni.showLoading({
        title: '支付中...',
        mask: true,
    });
    $post(`/human/packages/jsapi/pay/${item.id}?openId=${userInfo.value.wxOpenid}`).then(res => {
        if (res.orderNo) {
            uni.requestPayment({
                ...res.pay,
                success: () => {
                    uni.hideLoading();
                    uni.showToast({
                        title: '支付成功',
                        icon: 'success',
                    });
                    uni.redirectTo({
                        url: '/pages/my/components/order',
                    });
                },
                fail: e => {
                    uni.hideLoading();
                    uni.showToast({
                        title: '支付失败',
                        icon: 'none',
                    });
                },
            });
            return;
        }
        uni.hideLoading();
        uni.showToast({
            title: '支付失败',
            icon: 'none',
        });
    });
};
</script>

<template>
    <div class="human">
        <u-navbar title="会员套餐" placeholder autoBack></u-navbar>
        <div class="package-list" v-if="list.length > 0">
            <div class="package-item" v-for="item in list" :key="item.id">
                <!-- 标题 -->
                <div class="package-title">{{ item.name }}</div>

                <!-- 价格描述 -->
                <div class="price-section">
                    <div class="current-price">
                        <span class="price-symbol">¥</span>
                        <span class="price-value">{{ item.currentPrice }}</span>
                        <span class="price-unit">/{{ item.durationDays }}天</span>
                    </div>
                    <div class="original-price" v-if="item.originalPrice > item.currentPrice">
                        ¥{{ item.originalPrice }}
                    </div>
                </div>

                <!-- 立即购买按钮 -->
                <button class="buy-btn" @click="handleBuy(item)">立即购买</button>

                <!-- 描述 -->
                <div class="description" v-if="item.description">
                    <u-parse :content="item.description" />
                </div>
                <!-- 子项列表 -->
                <wd-collapse
                    v-if="item.features && item.features.length > 0"
                    v-model="collapseValues[item.id]"
                    class="features-collapse"
                >
                    <wd-collapse-item title="套餐详情" :name="item.name">
                        <div class="features-list">
                            <div
                                class="feature-item"
                                v-for="(feature, index) in item.features"
                                :key="index"
                            >
                                <div class="feature-content">
                                    {{ feature.price.name }} * {{ feature.num }} ({{
                                        formatUnit(feature.unit)
                                    }})
                                </div>
                            </div>
                        </div>
                    </wd-collapse-item>
                </wd-collapse>
            </div>
        </div>
        <div class="empty" v-else>
            <text>暂无套餐数据</text>
        </div>
    </div>
</template>

<style scoped lang="scss">
.human {
    padding: 20rpx;
    padding-bottom: 40rpx;
    background: #f5f5f5;
    min-height: 100vh;

    .package-list {
        display: flex;
        flex-direction: column;
        gap: 20rpx;

        .package-item {
            background: #fff;
            border-radius: 16rpx;
            padding: 30rpx 24rpx;
            display: flex;
            flex-direction: column;
            box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

            .package-title {
                font-size: 32rpx;
                font-weight: 600;
                color: #333;
                margin-bottom: 24rpx;
            }

            .price-section {
                display: flex;
                flex-direction: column;
                align-items: center;
                margin-bottom: 30rpx;

                .current-price {
                    display: flex;
                    align-items: baseline;
                    margin-bottom: 12rpx;

                    .price-symbol {
                        font-size: 32rpx;
                        color: #ff3b30;
                        font-weight: bold;
                        margin-right: 4rpx;
                    }

                    .price-value {
                        font-size: 52rpx;
                        color: #ff3b30;
                        font-weight: bold;
                        line-height: 1;
                    }

                    .price-unit {
                        font-size: 26rpx;
                        color: #333;
                        font-weight: normal;
                        margin-left: 6rpx;
                    }
                }

                .original-price {
                    font-size: 26rpx;
                    color: #a0a0a0;
                    text-decoration: line-through;
                }
            }

            .buy-btn {
                width: 100%;
                height: 88rpx;
                background: #ff9500;
                color: #fff;
                border: none;
                border-radius: 12rpx;
                font-size: 32rpx;
                font-weight: 500;
                margin-bottom: 24rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                box-shadow: 0 2rpx 8rpx rgba(255, 149, 0, 0.2);

                &:active {
                    background: #e68500;
                    opacity: 0.9;
                }
            }

            .description {
                font-size: 28rpx;
                color: #333;
                margin-bottom: 24rpx;
                word-break: break-all;
                text-justify: inter-word;
                white-space: pre-wrap;
                word-break: break-word;
                word-wrap: break-word;
                max-width: 100%;
                overflow-wrap: break-word;
            }

            .features-collapse {
                margin-top: 24rpx;
            }
            :deep(.wd-collapse-item__header) {
                padding: 15px 0 0 0;
            }
            :deep(.wd-collapse-item__body) {
                padding: 12px 0 0 0;
            }
            .features-list {
                display: flex;
                flex-direction: column;
                gap: 16rpx;

                .feature-item {
                    display: flex;
                    align-items: flex-start;
                    padding-left: 0;

                    &::before {
                        content: '';
                        width: 4rpx;
                        height: 36rpx;
                        background: #ff9500;
                        margin-right: 20rpx;
                        flex-shrink: 0;
                        border-radius: 2rpx;
                    }

                    .feature-content {
                        font-size: 26rpx;
                        color: #333;
                        line-height: 1.6;
                        flex: 1;
                    }
                }
            }
        }
    }

    .empty {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 60vh;
        color: #999;
        font-size: 28rpx;
    }
}
</style>
